package com.aidansmeaton.weightmanager;

import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.aidansmeaton.weightmanager.data.DatabaseHelper;
import com.aidansmeaton.weightmanager.util.TimeFormatter;

/** The first activity in the app. */
public class DiaryExerciseActivity extends ListActivity implements OnItemClickListener {

	private DatabaseHelper db;
	private String date;
	private Cursor c;

	private TextView completed;
	private TextView remaining;
	private ProgressBar progress;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.diary_exercise);

		db = DatabaseHelper.getInstance(this);
		date = this.getIntent().getStringExtra("Date");
		c = db.getExerciseLogsForDate(date);

		completed = (TextView) findViewById(R.id.exercise_completed);
		remaining = (TextView) findViewById(R.id.exercise_remaining);
		
		getListView().setOnItemClickListener(DiaryExerciseActivity.this);
	}

	@Override
	public void onResume() {
		super.onResume();

		c.requery();
		setListAdapter(new DiaryExerciseAdapter(this, c));
		
		progress = (ProgressBar) findViewById(R.id.minutes_progress);
        completed = (TextView) findViewById(R.id.exercise_completed);
        remaining = (TextView) findViewById(R.id.exercise_remaining);
        
    	progress.setProgress(0);
    	completed.setText("");
    	remaining.setText("");

        completed.setAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
        remaining.setAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
        
        int cumulativeMinutes = 0;
    	int goalMinutes = getSharedPreferences("Profile",0).getInt("ExerciseTarget", -1);
        
        String beginningOfWeek = TimeFormatter.getWeekBoundary(date,true);
        String endOfWeek = TimeFormatter.getWeekBoundary(date,false);
        Cursor weekCursor = db.getExerciseLogsBetweenDates(beginningOfWeek, endOfWeek);
        weekCursor.moveToFirst();
        while (!weekCursor.isAfterLast()){
        	cumulativeMinutes += weekCursor.getInt(DatabaseHelper.EXERCISE_LOG_MINUTES);
        	weekCursor.moveToNext();
        }
        weekCursor.close();
        
        // set values on header
        completed.setText("" + cumulativeMinutes);
        if (goalMinutes != -1) {
        	remaining.setText("" + (goalMinutes-cumulativeMinutes));
        	progress.setMax(goalMinutes);
        	progress.setProgress(cumulativeMinutes);
        } else {
        	progress.setVisibility(View.GONE);
        }

	}
	
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		recordExerciseClick(view);
    }

	public void recordExerciseClick(View v) {
		
		// check if record already exists
		int exercise_id = -1;
		try {
			exercise_id = (int)(Integer) v.getTag(R.id.exercise_row);
		} catch (Exception e) {
			// ignore
		}
		final int id = exercise_id;

		// initialise dialog
		final Dialog d = new Dialog(this);
		d.setTitle(getString(R.string.diary_exercise_record));
		d.setContentView(R.layout.dialog_record_exercise);

		// force width to fill parent
		LayoutParams params = d.getWindow().getAttributes();
		params.width = LayoutParams.FILL_PARENT;
		d.getWindow().setAttributes(
				(android.view.WindowManager.LayoutParams) params);

		// identify number pickers - set limits
		final EditText activity = (EditText) d.findViewById(R.id.activity);
		final EditText minutes = (EditText) d.findViewById(R.id.minutes);

		// identify buttons
		final Button okay = (Button) d.findViewById(R.id.okay_button);
		final Button cancel = (Button) d.findViewById(R.id.cancel_button);
		final Button remove = (Button) d.findViewById(R.id.remove_button);
		
		// fill views
		if (id != -1) {
			Cursor c = db.getExerciseLog(id);
			c.moveToFirst();
			activity.setText(c.getString(DatabaseHelper.EXERCISE_LOG_ACTIVITY));
			minutes.setText(""+c.getInt(DatabaseHelper.EXERCISE_LOG_MINUTES));
		}
		
		// set listener for okay button
		okay.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				try {
					String act = "" + activity.getText().toString();
					int mins = Integer.parseInt(minutes.getText().toString());
					if (id == -1) DiaryExerciseActivity.this.db.addExerciseLog(DiaryExerciseActivity.this.date, act, mins, -1);
					else DiaryExerciseActivity.this.db.editExerciseLog(id, DiaryExerciseActivity.this.date, act, mins, -1);
					d.dismiss();
					DiaryExerciseActivity.this.onResume();
				} catch (Exception e){
					Toast.makeText(DiaryExerciseActivity.this, "Enter the number of minutes.", Toast.LENGTH_SHORT).show();
				}
				
			}
		});

		// set listener for cancel button
		cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				d.dismiss();
			}
		});

		// set listener for remove button
		remove.setClickable(id != -1);
		remove.setEnabled(id != -1);
		if (id != -1) remove.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				DiaryExerciseActivity.this.db.removeExerciseLog(id);
				d.dismiss();
				DiaryExerciseActivity.this.onResume();
			}
		});

		// show dialog
		d.show();

	}

	private class DiaryExerciseAdapter extends CursorAdapter {

		private LayoutInflater inflater;

		public DiaryExerciseAdapter(Context context, Cursor cursor) {
			super(context, cursor);

			inflater = LayoutInflater.from(context);
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {

			// Set tag
			view.setTag(R.id.exercise_row, cursor.getInt(DatabaseHelper.EXERCISE_LOG_ID));

			// Identify textviews
			TextView minutesText = (TextView) view.findViewById(R.id.minutes);
			TextView activityText = (TextView) view.findViewById(R.id.activity);

			// Get cursor values
			int minutes = cursor.getInt(DatabaseHelper.EXERCISE_LOG_MINUTES);
			String activity = cursor.getString(DatabaseHelper.EXERCISE_LOG_ACTIVITY);
			
			// Fill view with cursor values
			minutesText.setText("" + minutes);
			activityText.setText(activity);

		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			return inflater.inflate(R.layout.diary_exercise_row_record, null);
		}
	}

}